package org.jeecg.modules.wmhb.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.FillRuleConstant;
import org.jeecg.common.constant.UserConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.modules.wmhb.entity.*;
import org.jeecg.modules.wmhb.service.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.wmhb.vo.WmProductTaskbookMapVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

/**
 * @Description: 合同表
 * @Author: jeecg-boot
 * @Date:   2024-09-02
 * @Version: V1.0
 */
@Api(tags="合同表")
@RestController
@RequestMapping("/wmhb/wmContract")
@Slf4j
public class WmContractController extends JeecgController<WmContract, IWmContractService> {
	@Autowired
	private IWmContractService wmContractService;
	@Autowired
	private IWmProjectService wmProjectService;
	@Autowired
	private IWmContractProductService wmContractProductService;
	@Autowired
	private IWmTaskbookService wmTaskbookService;
	@Autowired
	private IWmClientService wmClientService;
	@Autowired
	private ISysDictService sysDictService;
	@Autowired
	private IWmTaskService wmTaskService;
	@Autowired
	private IWmTaskBomService wmTaskBomService;
	
	/**
	 * 分页列表查询
	 *
	 * @param wmContract
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "合同表-分页列表查询")
	@ApiOperation(value="合同表-分页列表查询", notes="合同表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<WmContract>> queryPageList(WmContract wmContract,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<WmContract> queryWrapper = QueryGenerator.initQueryWrapper(wmContract, req.getParameterMap());
		Page<WmContract> page = new Page<WmContract>(pageNo, pageSize);
		queryWrapper.orderByDesc("create_time");
		IPage<WmContract> pageList = wmContractService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param wmContract
	 * @return
	 */
	@AutoLog(value = "合同表-添加")
	@ApiOperation(value="合同表-添加", notes="合同表-添加")
	@RequiresPermissions("wmhb:wm_contract:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody WmContract wmContract) {
		if(UserConstant.NOT_UNIQUE.equals(wmContractService.checkCodeUnique(wmContract))){
			return Result.error("新增合同失败，合同编码已存在");
		}
		if(UserConstant.NOT_UNIQUE.equals(wmContractService.checkNameUnique(wmContract))){
			return Result.error("新增合同失败，合同名称已存在");
		}

		if (StringUtils.isEmpty(wmContract.getCode())) {
			String code = (String) FillRuleUtil.executeRule(FillRuleConstant.CONTRACT, null);
			wmContract.setCode(code);
		}

		if(StringUtils.isEmpty(wmContract.getWeight())){
			wmContract.setWeight("1");
		}

		WmProject wmProject = wmProjectService.getById(wmContract.getWmProjectId());
		if(wmProject != null && wmProject.getStatus().equals(UserConstant.PROJECT_STATUS_PREPARE)){
			return Result.error("请先确认项目");
		}

		wmContractService.save(wmContract);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param wmContract
	 * @return
	 */
	@AutoLog(value = "合同表-编辑")
	@ApiOperation(value="合同表-编辑", notes="合同表-编辑")
	@RequiresPermissions("wmhb:wm_contract:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody WmContract wmContract) {
		if(UserConstant.NOT_UNIQUE.equals(wmContractService.checkCodeUnique(wmContract))){
			return Result.error("编辑合同"+ wmContract.getCode()+"失败，合同编码已存在");
		}
		if(UserConstant.NOT_UNIQUE.equals(wmContractService.checkNameUnique(wmContract))){
			return Result.error("编辑合同"+ wmContract.getCode()+"失败，合同名称已存在");
		}

		if(StringUtils.isEmpty(wmContract.getWeight())){
			wmContract.setWeight("1");
		}

		wmContractService.updateById(wmContract);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "合同表-通过id删除")
	@ApiOperation(value="合同表-通过id删除", notes="合同表-通过id删除")
	@RequiresPermissions("wmhb:wm_contract:delete")
	@DeleteMapping(value = "/delete")
	@Transactional
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		if(wmContractService.checkHasItem(id)){
			return Result.error("合同下有任务书，请先删除任务书");
		}
		wmContractService.removeById(id);
		wmContractProductService.removeByWmContractId(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "合同表-批量删除")
	@ApiOperation(value="合同表-批量删除", notes="合同表-批量删除")
	@RequiresPermissions("wmhb:wm_contract:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	@Transactional
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		List<String> oldIdList = Arrays.asList(ids.split(","));//前端参数
		List<String> newIdList = new ArrayList<>();   //可以删除的ID列表
		List<String> filterIdList = new ArrayList<>();//不能删除的ID列表
		for(String id: oldIdList){
			if(!wmContractService.checkHasItem(id)){
				newIdList.add(id);
			}
			else{
				filterIdList.add(id);
			}
		}

		String filterStr = String.join(",", filterIdList);
		if(!CollectionUtils.isEmpty(newIdList)) {
			wmContractService.removeByIds(newIdList);
			for(String id: newIdList) {
				wmContractProductService.removeByWmContractId(id);
			}

			if(CollectionUtils.isEmpty(filterIdList)) {
				return Result.OK("批量删除成功！");
			}
			else{
				String newStr = String.join(",", newIdList);
				return Result.OK("ID为" + newStr + "批量删除成功，ID为" + filterStr + "的删除失败，原因：合同下有任务书！");
			}
		}
		else{
			return Result.error("批量删除失败，原因：合同下有任务书！");
		}
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "合同表-通过id查询")
	@ApiOperation(value="合同表-通过id查询", notes="合同表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<WmContract> queryById(@RequestParam(name="id",required=true) String id) {
		WmContract wmContract = wmContractService.getById(id);
		if(wmContract==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(wmContract);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param wmContract
    */
    @RequiresPermissions("wmhb:wm_contract:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, WmContract wmContract) {
		List<WmContract> wmContractList = wmContractService.listBySearch(wmContract);
		return wmContractService.exportContractExcel(request, wmContractList);
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("wmhb:wm_contract:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, WmContract.class);
    }

	 /**
	  * 确认
	  *
	  * @param ids
	  * @return
	  */
	 @AutoLog(value = "合同表-确认")
	 @ApiOperation(value = "合同表-确认", notes = "合同表-确认")
	 @RequiresPermissions("wmhb:wm_contract:confirm")
	 @RequestMapping(value = "/confirm", method = {RequestMethod.PUT, RequestMethod.POST})
	 @Transactional
	 public Result<String> doConfirm(@RequestParam(name = "ids", required = true) String ids) {
		 List<String> idList = Arrays.asList(ids.split(","));
		 for(String id: idList) {
			 WmContract wmContract = wmContractService.getById(id);
			 if(!wmContract.getStatus().equals(UserConstant.CONTRACT_STATUS_PREPARE)){{
				 throw new RuntimeException("只有草稿状态能确认");
			 }}

			 //wmContract.setProgress("10");
			 wmContract.setStatus(UserConstant.CONTRACT_STATUS_CONFIRMED); //更新合同的状态
			 wmContractService.updateById(wmContract);
		 }
		 return Result.OK("操作成功");
	 }

	/**
	 * 完成
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "合同表-完成")
	@ApiOperation(value = "合同表-完成", notes = "合同表-完成")
	@RequiresPermissions("wmhb:wm_contract:finish")
	@Transactional
	@RequestMapping(value = "/finish", method = {RequestMethod.PUT, RequestMethod.POST})
	public Result<String> doFinish(@RequestParam(name = "ids", required = true) String ids) {
		List<String> idList = Arrays.asList(ids.split(","));
		for(String id: idList) {
			WmContract wmContract = wmContractService.getById(id);
			if(!wmContract.getStatus().equals(UserConstant.CONTRACT_STATUS_CONFIRMED)){{
				throw new RuntimeException("只有确认状态能确认");
			}}

			wmContract.setProgress("100");
			wmContract.setStatus(UserConstant.PROJECT_STATUS_FINISHED); //更新项目的状态
			wmContractService.updateById(wmContract);
		}
		return Result.OK("操作成功");
	}

	/**
	 * 通过id查询产品映射关系
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "合同表-通过id查询产品映射关系")
	@ApiOperation(value="合同表-通过id查询产品映射关系", notes="合同表-通过id查询产品映射关系")
	@GetMapping(value = "/productTaskbookMap")
	public Result<List<WmProductTaskbookMapVo>> productTaskbookMap(@RequestParam(name="id",required=true) String id) {
		WmContract wmContract = wmContractService.getById(id);
		if(wmContract==null) {
			return Result.error("未找到对应数据");
		}

		List<WmProductTaskbookMapVo> wmProductTaskbookMapVoList = new ArrayList<>();
		List<String> wmContractIdList = new ArrayList<>();
		wmContractIdList.add(id);
		List<String> wmContractProductList = wmContractProductService.selectNodeAndChildrenByContractIdList(wmContractIdList);
		if(!wmContractProductList.isEmpty()) {
			List<WmTaskbook> wmTaskbookList = wmTaskbookService.selectByContractProduct(wmContractProductList);
			WmClient wmClient = null;
			if(!StringUtils.isEmpty(wmContract.getWmClientId())) {
				wmClient = wmClientService.getById(wmContract.getWmClientId());
			}
			for(WmTaskbook wmTaskbook: wmTaskbookList){
				WmProductTaskbookMapVo wmProductTaskbookMapVo = new WmProductTaskbookMapVo();
				WmContractProduct wmContractProduct = wmContractProductService.getById(wmTaskbook.getWmContractProductId());
				WmContractProduct wmContractProductAncestor = null;
				List<String> ancestorIdList = Arrays.asList(wmContractProduct.getAncestors().split(","));
				if(ancestorIdList.size() > 1) {
					wmContractProductAncestor = wmContractProductService.getById(ancestorIdList.get(1));
				}
				else{
					wmContractProductAncestor = wmContractProduct;
				}

				wmProductTaskbookMapVo.setChildProductName(wmContractProduct.getName());
				wmProductTaskbookMapVo.setSpecification(wmContractProduct.getSpecification());
				wmProductTaskbookMapVo.setQuantity(wmContractProduct.getQuantity());
				if(!StringUtils.isEmpty(wmContractProduct.getUnitOfMeasure())) {
					String dictText = sysDictService.queryDictTextByKey(UserConstant.UNIT_OF_MESSURE, wmContractProduct.getUnitOfMeasure());
					wmProductTaskbookMapVo.setUnitOfMeasure(dictText);
				}
				wmProductTaskbookMapVo.setWmContractId(id);
				wmProductTaskbookMapVo.setProductCode(wmContractProductAncestor.getCode());
				wmProductTaskbookMapVo.setProductName(wmContractProductAncestor.getName());
				wmProductTaskbookMapVo.setWmTaskbookId(wmTaskbook.getCode());
				if(wmClient != null) {
					wmProductTaskbookMapVo.setCustomerName(wmClient.getCnName());
				}
				wmProductTaskbookMapVoList.add(wmProductTaskbookMapVo);
			}
		}
		return Result.OK(wmProductTaskbookMapVoList);
	}

	/**
	 * 通过id查询合同BOM列表
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "合同表-通过id查询产品映射关系")
	@ApiOperation(value="合同表-通过id查询产品映射关系", notes="合同表-通过id查询产品映射关系")
	@GetMapping(value = "/contractBomList")
	public Result<List<WmTaskBom>> contractBomList(@RequestParam(name="id",required=true) String id) {
		List<WmTaskBom> wmTaskBomList = new ArrayList<>();
		WmContract wmContract = wmContractService.getById(id);
		if (wmContract == null) {
			return Result.error("未找到对应数据");
		}

		List<String> wmContractIdList = new ArrayList<>();
		wmContractIdList.add(id);
		List<String> wmContractProductList = wmContractProductService.selectNodeAndChildrenByContractIdList(wmContractIdList);
		if(!wmContractProductList.isEmpty()) {
			List<WmTask> wmTaskList = wmTaskService.selectTaskByContractProduct(wmContractProductList);
			List<String> taskIdList = new ArrayList<>();//所有报料任务ID
			for (WmTask wmTaskItem : wmTaskList) {
				if (!StringUtils.isEmpty(wmTaskItem.getOrderTaskId()) && !taskIdList.contains(wmTaskItem.getOrderTaskId())) {
					taskIdList.add(wmTaskItem.getOrderTaskId());
				}

				//根节点任务没有OrderTaskId，将根节点任务ID加入（其实改版后所有的报料任务ID都是根节点任务ID，此处代码没有简化）
				if(wmTaskItem.getAncestors().equals(UserConstant.ANCESTOR_ZERO) && !taskIdList.contains(wmTaskItem.getId())){
					taskIdList.add(wmTaskItem.getId());
				}
			}

			//3、查询所有到货BOM列表
			if (!taskIdList.isEmpty()) {
				List<WmTaskBom> wmTaskBomListOfItem = wmTaskBomService.listByWmTaskIds(taskIdList);
				wmTaskBomList.addAll(wmTaskBomListOfItem);
			}
		}

		return Result.OK(wmTaskBomList);
	}
}
